package com.webvihar.access2db.activities;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.webvihar.access2db.R;
import com.webvihar.access2db.asynctasks.A2DbAsyncWebRequestTask;
import com.webvihar.access2db.builders.RunQueryBuilder;
import com.webvihar.access2db.model.QueryResult;
import com.webvihar.access2db.restapi.A2DbRunQueryRequest;
import com.webvihar.access2db.restapi.A2DbWebResult;
import com.webvihar.access2db.utils.PreferencesManager;

public class EditDatabaseActivity extends BaseActivity implements OnClickListener, OnKeyListener{

	private EditText nameTxt;
	private Button editDatabaseBtn;
	private TextView titleTxt;
	private ImageButton addButton;

	private String dbName;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		setContentView(R.layout.add_edit_delete_database);
		initDbName();
		initUI();
		setTitleBar();
		setListeners();
	}

	private void initDbName() {
		Bundle bundle = getIntent().getExtras();
		dbName = bundle.getString(KEY_DATABASE_NAME);
	}
	
	private void initUI() {
		nameTxt = (EditText)findViewById(R.id.add_edit_delete_database_name_txt);
		nameTxt.setText(dbName);
		editDatabaseBtn = (Button)findViewById(R.id.add_edit_delete_database_btn);
		editDatabaseBtn.setText(getResources().getString(R.string.edit_database_txt));
		editDatabaseBtn.setEnabled(false);
	}
	
	private void setTitleBar() {
		titleTxt = (TextView) findViewById(R.id.title_txt);
		titleTxt.setText(getString(R.string.database_txt));
		addButton = (ImageButton) findViewById(R.id.title_action_image_btn);
		addButton.setVisibility(View.GONE);
			
	}

	private void setListeners() {
		editDatabaseBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		addQueryToPref();
		startEditDbRequest();		
	}

	private void startEditDbRequest() {
		A2DbRunQueryRequest request = new A2DbRunQueryRequest();
		request.encoded = true;
		request.host = 	PreferencesManager.getString(getApplicationContext(), PREF_SESSION_HOST);
		request.port =  PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PORT);
		request.username = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_USERNAME);
		request.password = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PASSWORD);
		request.dbname = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_DBNAME);
		request.query = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_QUERY);
		request.requestDelegate = new RunQueryBuilder();
		new A2DbAsyncWebRequestTask(true, getApplicationContext(), runQueryRequestHandler, getProgressDialog()).execute(request);

	}
	private Handler runQueryRequestHandler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			A2DbWebResult<QueryResult> response = (A2DbWebResult<QueryResult>) msg.obj;
			if(response == null) {
				showToast("Response is null");
				EditDatabaseActivity.this.finish();
			} else if(response.entity == null) {
				showToast("Server not found...");
				EditDatabaseActivity.this.finish();
			} else if(response.entity.result == null){
				showToast(response.entity.error+"");
				EditDatabaseActivity.this.finish();
			} else {
				showToast(response.entity.result);
				EditDatabaseActivity.this.finish();
			}
		}
	};	   

	private void addQueryToPref() {
		PreferencesManager.setString(getApplicationContext(), PREF_SESSION_QUERY, getQueryBuilder().getEditDatabaseQuery(PreferencesManager.getString(getApplicationContext(), PREF_SESSION_DBNAME), nameTxt.getText().toString()));
	}

	@Override
	public boolean onKey(View view, int position, KeyEvent keyEvent) {
		if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
			return false;
		} else if(view.getId() == R.id.add_edit_delete_database_name_txt) {
			enableUpdateButton();
		}
		return false;
	}

	private void enableUpdateButton() {
		if(!nameTxt.getText().toString().equalsIgnoreCase(dbName)) {
			editDatabaseBtn.setEnabled(true);
		} else {
			editDatabaseBtn.setEnabled(false);
		}
	}


}
